package nyist.media.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 解决跨域问题
 *
 * @author : dcf
 **/
@Component
public class CorsInterceptor extends HandlerInterceptorAdapter {

    public static final String OPTIONS = "OPTIONS";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //接受任何域名的请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        //设置允许跨域的头信息
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type, token");
        response.setCharacterEncoding("UTF-8");
        //是否允许发送cookie
        response.setHeader("Access-Control-Allow-Credentials", "false");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        if ((OPTIONS.equals(request.getMethod()))) {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
            return true;
        }
        return true;
    }
}